<?php
// +----------------------------------------------------------------------
// | zhanshop-admin / BaseService.php    [ 2023/2/26 16:46 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2023 zhangqiquan All rights reserved.
// +----------------------------------------------------------------------
// | Author: Administrator <768617998@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\admin\v1\service;

use app\api\admin\v1\service\finder\BaseFinder;
use zhanshop\RamCache;
use zhanshop\App;

class BaseService{

    protected function setRoleMenu(int $roleId, array $menuIds){
        RamCache::set('rolemenu:'.$roleId, json_encode($menuIds));
    }

    public function permission(int $roleId, string $menuId){
        if($roleId === 0) return true;
        $rolemenu = RamCache::get('rolemenu:'.$roleId);
        if($rolemenu == false) App::error()->setError('角色菜单获取失败'.$menuId, 403);
        $rolemenu = json_decode($rolemenu, true);
        if($rolemenu && in_array($menuId, $rolemenu)) return true;
        App::error()->setError('您没有权限操作该菜单'.$menuId, 403);
    }

    public function getFinder(string $menuId){
        // 菜单权限检查
        $finderPath = __DIR__.DIRECTORY_SEPARATOR.'finder'.DIRECTORY_SEPARATOR.$menuId.'.php';
        if(!file_exists($finderPath)){
            $finder = new BaseFinder($menuId);
        }else{
            $class = get_called_class();
            $dir = substr($class,0, strrpos($class, '\\'));
            $class = $dir.'\\finder\\'.$menuId;
            $finder = new $class($menuId);
        }
        return $finder;
    }

    protected $menuData;
    public function init(string $menuId){
        $this->menuData = App::database()->model("system_menu")->where(['id' => $menuId])->field('id,title,table_names,pk,name,pid')->find();
        if($this->menuData == false) App::error()->setError('菜单:'.$menuId.',不存在', 404);
        $this->menuData['table_names'] = explode(',', $this->menuData['table_names']);
        return $this;
    }
}